import { reactive, ref } from 'vue'

// 用户类型枚举
export const USER_TYPES = {
  ENTERPRISE: 'enterprise',
  INDIVIDUAL: 'individual',
  GOVERNMENT: 'government',
  ACADEMIC: 'academic',
  
  // 新增四种场景类型
  BRAZIL_MANAGER: 'brazil_manager',        // 去巴西开公司的经理
  OXFORD_PHD: 'oxford_phd',                // 牛津大学博士
  ECOMMERCE_PARK: 'ecommerce_park',        // 跨境电商产业园
  MINING_COMPANY: 'mining_company'         // 出国企业（巴西铜矿）
}

// 用户等级枚举
export const USER_LEVELS = {
  BASIC: 'basic',
  PREMIUM: 'premium',
  VIP: 'vip',
  ENTERPRISE: 'enterprise'
}

// 当前用户状态
export const currentUser = reactive({
  id: null,
  name: '',
  email: '',
  type: USER_TYPES.INDIVIDUAL,
  level: USER_LEVELS.BASIC,
  isLoggedIn: false,
  profile: {},
  preferences: {}
})

// 用户类型配置
export const userTypeConfigs = {
  [USER_TYPES.ENTERPRISE]: {
    name: '企业用户',
    description: '为企业提供专业的跨境政策服务',
    features: [
      'enterprise_dashboard',
      'bulk_policy_analysis',
      'compliance_monitoring',
      'team_collaboration',
      'advanced_analytics',
      'dedicated_agent',
      'priority_support'
    ],
    agentServices: [
      'policy_monitoring',
      'compliance_alerts',
      'risk_assessment',
      'opportunity_identification',
      'automated_reporting'
    ],
    dashboardSections: [
      'company_overview',
      'policy_compliance',
      'risk_dashboard',
      'opportunity_tracker',
      'team_management',
      'reporting_center'
    ]
  },
  
  [USER_TYPES.INDIVIDUAL]: {
    name: '个人用户',
    description: '为个人提供定制化的政策信息服务',
    features: [
      'personal_dashboard',
      'policy_recommendations',
      'bookmark_system',
      'notification_center',
      'basic_analytics'
    ],
    agentServices: [
      'personal_recommendations',
      'deadline_reminders',
      'policy_updates',
      'basic_analysis'
    ],
    dashboardSections: [
      'personal_overview',
      'recommended_policies',
      'saved_policies',
      'notification_center',
      'personal_analytics'
    ]
  },
  
  [USER_TYPES.GOVERNMENT]: {
    name: '政府机构',
    description: '为政府机构提供政策制定和监管支持',
    features: [
      'government_dashboard',
      'policy_impact_analysis',
      'public_service_tools',
      'inter_government_communication',
      'policy_drafting_assistance'
    ],
    agentServices: [
      'policy_impact_monitoring',
      'regulatory_compliance',
      'public_feedback_analysis',
      'inter_agency_coordination'
    ],
    dashboardSections: [
      'policy_overview',
      'impact_analysis',
      'public_engagement',
      'regulatory_compliance',
      'inter_agency_communication'
    ]
  },
  
  [USER_TYPES.ACADEMIC]: {
    name: '学术研究',
    description: '为学术机构提供研究和分析工具',
    features: [
      'research_dashboard',
      'data_analysis_tools',
      'research_collaboration',
      'publication_support',
      'advanced_search'
    ],
    agentServices: [
      'research_assistance',
      'data_collection',
      'trend_analysis',
      'literature_review'
    ],
    dashboardSections: [
      'research_overview',
      'data_analysis',
      'collaboration_hub',
      'publication_tracker',
      'advanced_search'
    ]
  },
  
  [USER_TYPES.BRAZIL_MANAGER]: {
    name: '国际投资经理',
    description: '准备在巴西开设公司的投资经理',
    scenario: '巴西投资开公司',
    avatar: '🇧🇷',
    level: 'premium',
    features: [
      'brazil_tax_comparison',      // 巴西税收政策对比
      'business_environment',       // 营商环境评估
      'investment_incentives',      // 投资激励政策
      'legal_compliance',           // 法律合规指导
      'market_analysis',           // 市场分析
      'company_registration'       // 公司注册流程
    ],
    agentServices: [
      'brazil_policy_advisor',     // 巴西政策顾问
      'legal_compliance_checker',  // 法律合规检查
      'tax_optimization_advisor',  // 税务优化顾问
      'market_intelligence'       // 市场情报
    ],
    dashboardSections: [
      'brazil_regions_comparison', // 巴西区域对比
      'tax_policy_analysis',      // 税收政策分析
      'investment_opportunities',  // 投资机会
      'regulatory_updates'        // 监管更新
    ],
    primaryCountries: ['巴西', '中国'],
    primaryIndustries: ['投资', '制造业', '服务业'],
    policyFocus: ['投资政策', '税收政策', '贸易政策', '监管政策']
  },
  
  [USER_TYPES.OXFORD_PHD]: {
    name: '海归博士',
    description: '牛津大学大气监测专业博士，准备回国发展',
    scenario: '博士后回国发展',
    avatar: '🎓',
    level: 'academic',
    features: [
      'talent_policies',           // 人才政策
      'research_funding',          // 科研资助
      'city_comparison',           // 城市对比
      'academic_positions',        // 学术职位
      'visa_immigration',          // 签证移民
      'housing_subsidies'         // 住房补贴
    ],
    agentServices: [
      'talent_policy_advisor',     // 人才政策顾问
      'research_funding_finder',   // 科研资助查找
      'city_selection_advisor',    // 城市选择顾问
      'career_development'        // 职业发展
    ],
    dashboardSections: [
      'talent_policies_by_city',   // 各城市人才政策
      'research_opportunities',    // 科研机会
      'living_conditions',         // 生活条件
      'academic_resources'        // 学术资源
    ],
    primaryCountries: ['中国', '英国'],
    primaryIndustries: ['科研', '环保', '大气监测', '教育'],
    policyFocus: ['人才政策', '科研政策', '教育政策', '环保政策']
  },
  
  [USER_TYPES.ECOMMERCE_PARK]: {
    name: '跨境电商产业园',
    description: '跨境电商产业园区管理者',
    scenario: '产业园区运营',
    avatar: '🏢',
    level: 'enterprise',
    features: [
      'park_incentives',           // 产业园优惠
      'customs_policies',          // 海关政策
      'export_support',            // 出口支持
      'tenant_services',           // 租户服务
      'logistics_optimization',    // 物流优化
      'digital_trade'             // 数字贸易
    ],
    agentServices: [
      'park_policy_advisor',       // 产业园政策顾问
      'customs_compliance',        // 海关合规
      'export_optimization',       // 出口优化
      'tenant_support'            // 租户支持
    ],
    dashboardSections: [
      'park_performance',          // 园区绩效
      'policy_utilization',        // 政策利用率
      'tenant_analytics',          // 租户分析
      'trade_statistics'          // 贸易统计
    ],
    primaryCountries: ['中国', '全球'],
    primaryIndustries: ['电商', '跨境贸易', '物流', '数字经济'],
    policyFocus: ['产业政策', '贸易政策', '物流政策', '数字政策']
  },
  
  [USER_TYPES.MINING_COMPANY]: {
    name: '矿业出口企业',
    description: '在巴西经营铜矿开采和出口的中国企业',
    scenario: '海外矿业投资',
    avatar: '⛏️',
    level: 'enterprise',
    features: [
      'mining_regulations',        // 矿业法规
      'export_procedures',         // 出口程序
      'environmental_compliance',  // 环保合规
      'commodity_policies',        // 大宗商品政策
      'bilateral_agreements',      // 双边协议
      'supply_chain_security'     // 供应链安全
    ],
    agentServices: [
      'mining_policy_advisor',     // 矿业政策顾问
      'export_compliance',         // 出口合规
      'environmental_monitor',     // 环保监管
      'commodity_intelligence'    // 大宗商品情报
    ],
    dashboardSections: [
      'mining_operations',         // 矿业运营
      'export_performance',        // 出口表现
      'compliance_status',         // 合规状态
      'market_trends'             // 市场趋势
    ],
    primaryCountries: ['中国', '巴西'],
    primaryIndustries: ['矿业', '有色金属', '出口贸易'],
    policyFocus: ['矿业政策', '出口政策', '环保政策', '投资政策']
  }
}

// 用户服务类
class UserService {
  constructor() {
    this.loadUserFromStorage()
    
    // 如果当前用户是企业用户且名称还是旧的，更新为新名称
    if (currentUser.isLoggedIn && 
        currentUser.type === USER_TYPES.ENTERPRISE && 
        (currentUser.name === '华为技术有限公司' || currentUser.profile?.companyName === '华为技术有限公司')) {
      currentUser.name = '张先生'
      if (currentUser.profile) {
        currentUser.profile.companyName = '张先生'
      }
      this.saveUserToStorage()
    }
  }

  // 登录
  login(userData) {
    Object.assign(currentUser, {
      ...userData,
      isLoggedIn: true
    })
    this.saveUserToStorage()
    return Promise.resolve(currentUser)
  }

  // 登出
  logout() {
    Object.assign(currentUser, {
      id: null,
      name: '',
      email: '',
      type: USER_TYPES.INDIVIDUAL,
      level: USER_LEVELS.BASIC,
      isLoggedIn: false,
      profile: {},
      preferences: {}
    })
    this.clearUserFromStorage()
  }

  // 切换用户类型（演示用）
  switchUserType(userType) {
    if (userTypeConfigs[userType]) {
      currentUser.type = userType
      this.saveUserToStorage()
      return true
    }
    return false
  }

  // 快速场景登录
  quickScenarioLogin(userType) {
    if (userTypeConfigs[userType]) {
      const mockData = this.getMockUserData(userType)
      Object.assign(currentUser, {
        ...mockData,
        isLoggedIn: true
      })
      this.saveUserToStorage()
      return Promise.resolve(currentUser)
    }
    return Promise.reject(new Error('Invalid user type'))
  }

  // 获取用户类型配置
  getUserTypeConfig(userType = currentUser.type) {
    return userTypeConfigs[userType] || userTypeConfigs[USER_TYPES.INDIVIDUAL]
  }

  // 检查用户是否有特定功能权限
  hasFeature(feature) {
    const config = this.getUserTypeConfig()
    return config.features.includes(feature)
  }

  // 获取用户的Agent服务
  getAgentServices() {
    const config = this.getUserTypeConfig()
    return config.agentServices
  }

  // 获取用户的仪表板部分
  getDashboardSections() {
    const config = this.getUserTypeConfig()
    return config.dashboardSections
  }

  // 模拟用户数据
  getMockUserData(userType) {
    const mockData = {
      [USER_TYPES.ENTERPRISE]: {
        id: 1,
        name: '张先生',
        email: 'admin@huawei.com',
        type: USER_TYPES.ENTERPRISE,
        level: USER_LEVELS.ENTERPRISE,
        profile: {
          companyName: '张先生',
          industry: '电信设备制造',
          scale: '大型企业',
          regions: ['中国', '美国', '欧盟', '东南亚'],
          employees: 195000,
          revenue: '8914亿元'
        },
        preferences: {
          focusPolicies: ['tax', 'trade', 'investment', 'compliance'],
          regions: ['china', 'usa', 'eu', 'asean'],
          alertFrequency: 'realtime'
        }
      },
      
      [USER_TYPES.INDIVIDUAL]: {
        id: 2,
        name: '张先生',
        email: 'zhang@example.com',
        type: USER_TYPES.INDIVIDUAL,
        level: USER_LEVELS.PREMIUM,
        profile: {
          age: 35,
          occupation: '跨境电商从业者',
          interests: ['税收优惠', '贸易便利化'],
          location: '深圳'
        },
        preferences: {
          focusPolicies: ['tax', 'ecommerce'],
          regions: ['china', 'usa'],
          alertFrequency: 'daily'
        }
      },
      
      [USER_TYPES.GOVERNMENT]: {
        id: 3,
        name: '商务部贸易司',
        email: 'trade@mofcom.gov.cn',
        type: USER_TYPES.GOVERNMENT,
        level: USER_LEVELS.VIP,
        profile: {
          department: '商务部贸易司',
          jurisdiction: '全国',
          responsibilities: ['对外贸易政策制定', '贸易促进'],
          level: '部级'
        },
        preferences: {
          focusPolicies: ['trade', 'investment', 'compliance'],
          regions: ['global'],
          alertFrequency: 'immediate'
        }
      },
      
      [USER_TYPES.ACADEMIC]: {
        id: 4,
        name: '北京大学国际经济研究中心',
        email: 'research@pku.edu.cn',
        type: USER_TYPES.ACADEMIC,
        level: USER_LEVELS.PREMIUM,
        profile: {
          institution: '北京大学',
          department: '国际经济研究中心',
          researchFields: ['国际贸易政策', '全球经济治理'],
          projects: ['一带一路政策研究', 'RCEP影响评估'],
          publications: 156
        },
        preferences: {
          focusPolicies: ['trade', 'investment', 'research'],
          regions: ['global'],
          alertFrequency: 'weekly'
        }
      },

      [USER_TYPES.BRAZIL_MANAGER]: {
        id: 5,
        name: '李明',
        email: 'li.ming@chinabrazil.com',
        type: USER_TYPES.BRAZIL_MANAGER,
        level: USER_LEVELS.PREMIUM,
        profile: {
          company: '中巴投资有限公司',
          position: '巴西区域总经理',
          industry: '制造业',
          targetCountry: '巴西',
          targetStates: ['圣保罗州', '里约热内卢州', '米纳斯吉拉斯州'],
          experience: '15年国际投资经验',
          investmentSize: '5000万美元',
          businessType: '制造业分公司设立',
          bio: '资深国际投资经理，专注于南美市场开发，计划在巴西建立汽车零部件制造基地'
        },
        preferences: {
          focusPolicies: ['investment', 'tax', 'trade', 'compliance'],
          regions: ['brazil', 'china'],
          alertFrequency: 'daily'
        }
      },

      [USER_TYPES.OXFORD_PHD]: {
        id: 6,
        name: '张博士',
        email: 'zhang.phd@oxford.ac.uk',
        type: USER_TYPES.OXFORD_PHD,
        level: USER_LEVELS.ACADEMIC,
        profile: {
          degree: '牛津大学环境科学博士',
          institution: '牛津大学',
          major: '大气监测与环境科学',
          researchFocus: '空气质量监测技术',
          publications: 28,
          citations: 1580,
          targetCities: ['北京', '上海', '深圳', '杭州', '成都'],
          careerGoal: '回国从事科研工作',
          preferredInstitutions: ['清华大学', '北京大学', '中科院'],
          bio: '牛津大学环境科学博士，专注于大气监测技术研究，希望回国继续从事环境科学研究'
        },
        preferences: {
          focusPolicies: ['talent', 'research', 'education', 'environment'],
          regions: ['china', 'uk'],
          alertFrequency: 'weekly'
        }
      },

      [USER_TYPES.ECOMMERCE_PARK]: {
        id: 7,
        name: '王园长',
        email: 'wang@szecpark.com',
        type: USER_TYPES.ECOMMERCE_PARK,
        level: USER_LEVELS.ENTERPRISE,
        profile: {
          parkName: '深圳跨境电商产业园',
          position: '园区管理委员会主任',
          location: '深圳前海',
          parkSize: '15万平方米',
          tenantCount: 500,
          mainIndustries: ['跨境电商', '数字贸易', '物流服务'],
          establishedYear: 2018,
          totalRevenue: '120亿元',
          exportValue: '35亿美元',
          bio: '管理着华南地区最大的跨境电商产业园，致力于为电商企业提供全方位政策支持'
        },
        preferences: {
          focusPolicies: ['ecommerce', 'trade', 'logistics', 'digital'],
          regions: ['china', 'global'],
          alertFrequency: 'daily'
        }
      },

      [USER_TYPES.MINING_COMPANY]: {
        id: 8,
        name: '陈总',
        email: 'chen@chinabrazilmining.com',
        type: USER_TYPES.MINING_COMPANY,
        level: USER_LEVELS.ENTERPRISE,
        profile: {
          company: '中巴矿业集团',
          position: '海外事业部总经理',
          industry: '有色金属开采',
          targetCountry: '巴西',
          miningLocations: ['米纳斯吉拉斯州', '帕拉州'],
          products: ['铜矿石', '铁矿石'],
          annualProduction: '100万吨铜矿石',
          employees: 2800,
          operatingYears: 8,
          exportValue: '8亿美元',
          bio: '中巴矿业集团海外事业部总经理，负责巴西铜矿开采业务，是中巴贸易的重要参与者'
        },
        preferences: {
          focusPolicies: ['mining', 'export', 'environment', 'investment'],
          regions: ['brazil', 'china'],
          alertFrequency: 'daily'
        }
      }
    }
    
    return mockData[userType] || mockData[USER_TYPES.INDIVIDUAL]
  }

  // 保存用户到本地存储
  saveUserToStorage() {
    localStorage.setItem('currentUser', JSON.stringify(currentUser))
  }

  // 从本地存储加载用户
  loadUserFromStorage() {
    const userData = localStorage.getItem('currentUser')
    if (userData) {
      const parsed = JSON.parse(userData)
      Object.assign(currentUser, parsed)
    }
  }

  // 清除本地存储的用户数据
  clearUserFromStorage() {
    localStorage.removeItem('currentUser')
  }
}

export const userService = new UserService()
export default userService 